<script setup lang="ts">
import { Graph } from '@antv/x6'
import { UploadUserFile } from 'element-plus'
import YkUploadImage from '@yk/components/upload/upload-image/YkUploadImage.vue'
import { CircleClose } from '@element-plus/icons-vue'
import { useYkEditorDrawStore } from '../../../store'
import { eventBus } from '../../../utils'

const store = useYkEditorDrawStore()

// region TODO 画布大小
function initGraphSize () {
  const { width, height } = store.size
  graphSize.value = `${width} x ${height}`
}

const graphSize = ref('')
function setGraphSize () {
  const [width, height] = graphSize.value.split(' x ').map(item => Number(item))
  const zoom = store.graph.zoom()
  store.graph.zoomTo(1)
  store.graph.options.width = width
  store.graph.options.height = height
  store.size = { width, height }
  store.graph.zoomTo(zoom)
}
// region TODO 自定义画布大小
const graphSizeDialogModel = ref(false)
const graphSizeDialogForm = ref({ width: 1920, height: 1080 })
// 提交
function submitGraphSizeDialog () {
  const { width, height } = graphSizeDialogForm.value
  graphSize.value = width + ' x ' + height
  setGraphSize()
  graphSizeDialogModel.value = false
}
// endregion
// endregion

// region TODO 背景
function initBackground () {
  let background = getBackgroundOptions()
  if (!background) {
    const { width, height } = backgroundSize.value
    const { x, y } = backgroundPosition.value
    const options = { size: `${width} ${height}`, position: `${x} ${y}` }
    store.graph.background.draw(options)
    background = options
  } else {
    const [width, height] = (background.size as string).split(' ')
    backgroundSize.value = { width, height }
    const [x, y] = ((background.position || 'center center') as string).split(' ')
    backgroundPosition.value = { x, y }
    const { color, repeat, opacity } = background
    backgroundAttrs.value = { color, repeat, opacity }
  }
  currentBackgroundImage.value = background.image
  eventBus.on('uploadedFile', bgUploadedFiled)
}

// region TODO 背景图片
const currentBackgroundImage = shallowRef()
const bgUploadUserFile = shallowRef<UploadUserFile>()
function getBackgroundOptions () {
  console.log(store.graph.background.options)
  return store.graph.background.options.background as Graph.BackgroundManager.Options
}
// 背景图片选择
function bgUploadImageChangeHandle (e: UploadUserFile) {
  store.graph.background.draw({
    ...getBackgroundOptions(),
    image: e.url
  })
  store.background.file = e.raw
}

// 背景图片取消选择
function bgUploadImageRemoveHandle () {
  store.graph.background.draw({
    ...getBackgroundOptions(),
    image: currentBackgroundImage.value
  })
}

// 背景图片移除
function removeBackgroundImage () {
  ElMessageBox.confirm('确认移除背景图片？操作后无法撤销，如想替换图片可点击图片进行替换', '移除提醒').then(() => {
    store.graph.background.draw({
      ...getBackgroundOptions(),
      image: undefined
    })
    currentBackgroundImage.value = undefined
  })
}

// 文件上传后
function bgUploadedFiled (newUrl: string | unknown) {
  currentBackgroundImage.value = newUrl
  bgUploadUserFile.value = null
  bgUploadImageRemoveHandle()
}
// endregion

// region TODO 背景属性
const backgroundAttrs = ref({
  // 背景颜色
  color: '',
  // 背景重复
  repeat: 'no-repeat',
  // 背景透明度
  opacity: 1
})

watch(backgroundAttrs, () => {
  store.graph.background.draw({
    ...getBackgroundOptions(),
    ...backgroundAttrs.value
  })
}, { deep: true })

// TODO 背景大小
const backgroundSize = ref({ width: '100%', height: '100%' })
watch(backgroundSize, () => {
  let { width, height } = backgroundSize.value
  !isNaN(Number(width)) && (width = width + 'px')
  !isNaN(Number(height)) && (height = height + 'px')
  store.graph.background.draw({
    ...getBackgroundOptions(),
    size: `${width} ${height}`
  })
}, { deep: true })

// TODO 背景位置
const backgroundPosition = ref({ x: 'center', y: 'center' })
watch(backgroundPosition, () => {
  let { x, y } = backgroundPosition.value
  !isNaN(Number(x)) && (x = x + 'px')
  !isNaN(Number(y)) && (y = y + 'px')
  store.graph.background.draw({
    ...getBackgroundOptions(),
    position: `${x} ${y}`
  })
}, { deep: true })
// endregion
// endregion

// region TODO 网格
function initGrid () {
  const grid = store.graph.grid.options.grid
  if (grid.args) {
    gridAttrs.value = store.graph.grid.options.grid as any
  }

  store.graph.grid.draw({ ...gridAttrs.value })
}

const gridAttrs = ref({
  size: 10,
  type: 'dot',
  args: [
    {
      color: '#BABBBE', // 主网格线颜色
      thickness: 1, // 主网格线宽度
      factor: null
    },
    {
      color: '#ddd', // 次网格线颜色
      thickness: 2, // 次网格线宽度
      factor: 5 // 主次网格线间隔
    }
  ]
})
watch(gridAttrs, () => {
  store.graph.grid.draw({ ...gridAttrs.value })
}, { deep: true })
// endregion

// region TODO 初始化
const stopInitWatch = watch(() => store.graph, () => {
  if (store.graph) {
    initAttrsBar()
    nextTick(() => stopInitWatch())
  }
}, { immediate: true })
function initAttrsBar () {
  // 画布大小
  initGraphSize()
  // 背景
  initBackground()
  // 网格
  initGrid()
  // const _config = graph.value.options._config
  // graphSize.value = _config.width + ' x ' + _config.height
  // showPorts.value = globalResources.value.showPorts
  // backgroundColor.value = globalResources.value.flowContainerStyle.backgroundColor
  // dataFrequency.value = graph.value.options._config.dataFrequency
  // if (graph.value.options._config.backgroundImage) {
  //   currentImageUrl.value = settings.IMAGE_PREFIX + graph.value.options._config.backgroundImage
  // } else {
  //   currentImageUrl.value = null
  // }
  // if (graph.value.options._config.backgroundFile) {
  //   uploadImageList.value = [{ url: URL.createObjectURL(graph.value.options._config.backgroundFile), status: 'ready' }]
  // }
}
// endregion

//
// // region TODO 数据频率
// const dataFrequency = ref(5000)
// function setDataFrequency () {
//   graph.value.options._config.dataFrequency = dataFrequency.value
// }
// // endregion

// region TODO 折叠面板
const collapseNames = ref(['基础属性', '网格'])
// endregion
</script>

<template v-if="store.graph">
  <el-collapse v-model="collapseNames">
    <el-collapse-item title="基础属性" name="基础属性">
      <div class="attr-grid">
        <el-form-item label="画布大小" style="grid-column: 1 / 3">
          <el-select v-model="graphSize" class="w-100" popper-class="select--graph-size" @change="setGraphSize">
            <el-option value="800 x 600" />
            <el-option value="1920 x 1080" />
            <el-option class="option-custom" :value="graphSize" @click="graphSizeDialogModel = true">自定义</el-option>
          </el-select>
        </el-form-item>
        <!--画布大小-->
        <el-dialog v-model="graphSizeDialogModel" title="画布大小" width="300px" append-to-body>
          <el-form label-width="60px">
            <el-form-item label="画布宽">
              <el-input-number v-model="graphSizeDialogForm.width" :min="100" />
            </el-form-item>
            <el-form-item label="画布高">
              <el-input-number v-model="graphSizeDialogForm.height" :min="100" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button size="default" type="primary" @click="submitGraphSizeDialog">确定</el-button>
          </template>
        </el-dialog>
      </div>
    </el-collapse-item>
    <el-collapse-item title="背景" name="背景">
      <el-form-item label="背景图片">
        <yk-upload-image v-model="bgUploadUserFile" width="100%" @change="bgUploadImageChangeHandle" @remove="bgUploadImageRemoveHandle">
          <div v-if="currentBackgroundImage" class="position-relative wh-100">
            <el-icon
              class="position-absolute" style="color: var(--yk-color-danger);font-size: 16px;right: 0;"
              @click.stop="removeBackgroundImage"
            >
              <CircleClose />
            </el-icon>
            <img :src="currentBackgroundImage" alt="" class="wh-100" style="object-fit: contain">
          </div>
        </yk-upload-image>
      </el-form-item>
      <el-form-item label="背景大小">
        <div class="attr-grid">
          <el-input v-model="backgroundSize.width">
            <template #prepend>宽</template>
          </el-input>
          <el-input v-model="backgroundSize.height">
            <template #prepend>高</template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="背景位置">
        <div class="attr-grid">
          <el-input v-model="backgroundPosition.x">
            <template #prepend>X</template>
          </el-input>
          <el-input v-model="backgroundPosition.y">
            <template #prepend>Y</template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="背景重复">
        <el-select v-model="backgroundAttrs.repeat" class="w-100">
          <el-option value="repeat" label="重复（repeat）" />
          <el-option value="repeat-x" label="重复X（repeat-x）" />
          <el-option value="repeat-y" label="重复Y（repeat-y）" />
          <el-option value="no-repeat" label="不重复（no-repeat）" />
        </el-select>
      </el-form-item>
      <el-form-item label="背景颜色">
        <el-color-picker v-model="backgroundAttrs.color" show-alpha />
      </el-form-item>
      <el-form-item label="背景透明度">
        <el-slider
          v-model="backgroundAttrs.opacity"
          class="px-2" size="small" :min="0"
          :max="1" :step="0.01"
        />
      </el-form-item>
    </el-collapse-item>
    <el-collapse-item title="网格" name="网格">
      <el-form-item label="网格类型">
        <el-select v-model="gridAttrs.type" class="w-100">
          <el-option value="dot" label="点状网格" />
          <el-option value="mesh" label="网状网格" />
          <el-option value="doubleMesh" label="双线网状网格" />
        </el-select>
      </el-form-item>
      <el-form-item label="网格大小">
        <el-slider
          v-model="gridAttrs.size"
          class="px-2" size="small" :min="1"
          :max="100" :step="1"
        />
      </el-form-item>
      <div class="attr-grid">
        <p v-if="gridAttrs.type === 'doubleMesh'" class="fs-12 text-color-regular" style="grid-column: 1 / 3">主网格</p>
        <el-form-item label="颜色">
          <el-color-picker v-model="gridAttrs.args[0].color" />
        </el-form-item>
        <el-form-item label="粗细">
          <el-input-number v-model="gridAttrs.args[0].thickness" />
        </el-form-item>
        <template v-if="gridAttrs.type === 'doubleMesh'">
          <p class="fs-12 text-color-regular" style="grid-column: 1 / 3">次网格</p>
          <el-form-item label="颜色">
            <el-color-picker v-model="gridAttrs.args[1].color" />
          </el-form-item>
          <el-form-item label="粗细">
            <el-input-number v-model="gridAttrs.args[1].thickness" />
          </el-form-item>
          <el-form-item label="主次网格比" style="grid-column: 1 / 3">
            <el-slider
              v-model="gridAttrs.args[1].factor"
              class="px-2" size="small" :min="1"
              :max="100" :step="1"
            />
          </el-form-item>
        </template>
      </div>
    </el-collapse-item>
    <!--<el-collapse-item title="操作" name="操作">-->
    <!--  <div class="d-grid" style="grid-template-columns: repeat(2, 1fr);">-->
    <!--    <el-form-item label="连接桩">-->
    <!--      <el-switch :model-value="showPorts" @click="portsToggle" />-->
    <!--    </el-form-item>-->
    <!--  </div>-->
    <!--</el-collapse-item>-->
    <!--<el-collapse-item title="数据" name="数据">-->
    <!--  <div class="d-grid" style="grid-template-columns: repeat(2, 1fr);">-->
    <!--    <el-form-item label="抓取频率(ms)">-->
    <!--      <el-input-number v-model="dataFrequency" :step="1000" :min="3000" @change="setDataFrequency" />-->
    <!--    </el-form-item>-->
    <!--  </div>-->
    <!--</el-collapse-item>-->
  </el-collapse>
</template>

<style lang="scss" scoped>
.select--graph-size {
  .option-custom.el-select-dropdown__item.selected {
    color: var(--el-text-color-regular);
    font-weight: normal;
  }
}

</style>
